package com.csw.shuanfa.utils.jwt;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

public class JwtUtil {

	/**
	 *
	 * @param id
	 * @param subject
	 * @param roles
	 * @param key
	 * @param seconds
	 * @return
	 */
	public String createjwt(String id, String subject, String roles,String key,int seconds) {
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		JwtBuilder builder = Jwts.builder().
				setId(id).
				setSubject(subject).
				setIssuedAt(now)
				.signWith(SignatureAlgorithm.HS256, key).
				claim("roles", roles);
		if (StringUtils.isNotEmpty(seconds+"")) {
			builder.setExpiration(new Date(nowMillis + seconds*1000));
		}
		return builder.compact();
	}


	public Claims parsejwt(String token, String key) {
		Claims claims = null;
		try {
			claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
			System.out.println("id]" + claims.getId());
			System.out.println("账号】" + claims.getSubject());
			System.out.println("签发时间】" + claims.getIssuedAt());
			System.out.println("角色】" + claims.get("roles"));
		} catch (ExpiredJwtException e) {
			System.out.println("认证失效");
			e.printStackTrace();
		}  catch (SignatureException e) {
			System.out.println("签名失效");
			e.printStackTrace();
		}
		return claims;
	}

}
